<template>
  <view class="refund-page">
    <!-- 订单信息 -->
    <view class="order-info">
      <view class="order-goods">
        <image :src="goodsImageUrl" mode="widthFix" class="goods-img"></image>
        <view class="goods-info">
          <view class="goods-name">{{ goodsName }}</view>
          <view class="goods-price">{{ goodsPrice }}</view>
        </view>
      </view>
      <view class="order-amount">
        <view class="order-amount_price">
          <view class="amount-label">退款金额 </view>
          <view class="amount-value">{{ refundAmount }}</view>
        </view>
        <view class="msg">1-3个工作日退还至原支付方，以实际退款为准</view>
      </view>
    </view>

    <!-- 退款原因 -->
    <view class="refund-reason" @click="openReasonPopup">
      <view class="order-amount_price">
        <view class="reason-label">
          退款原因
          <image src="/static/home/x.png" mode="widthFix"></image>
        </view>
        <view class="reason-value">
          {{ selectedReason || "请选择退款原因" }}
          <image src="/static/arrow_right.png" mode="widthFix"></image>
        </view>
      </view>
      <view class="msg">1-3个工作日退还至原支付方，以实际退款为准</view>
    </view>

    <!-- 退款说明 -->
    <view class="refund-description">
      <view class="desc-label">退款说明（选填）</view>
      <textarea 
        v-model="refundForm.description" 
        placeholder="补充退款原因详情。" 
        maxlength="200"
        class="desc-input"
        :rows="4"
      ></textarea>
      <view class="desc-count">{{ descCount }}</view>
    </view>

    <!-- 提交按钮 -->
    <view class="cofitng">
      <view class="prce">
        <view>应退：</view>
        <view>{{ shouldRefundAmount }}</view>
      </view>
      <view class="btn" @click="submitRefund">提交</view>
    </view>

    <!-- 退款原因弹窗 -->
    <view class="reason-popup" v-if="isReasonPopupVisible">
      <view class="popup-mask" @click="closeReasonPopup"></view>
      <view class="popup-content">
        <view class="popup-title">选择退款原因</view>
        <view class="reason-options">
          <view 
            class="reason-item" 
            v-for="(item, index) in reasonList" 
            :key="index"
            :class="{ active: selectedReasonId === item.id }"
            @click="selectReason(item.id, item.text)"
          >
            <view class="reason-text">{{ item.text }}</view>
            <image 
              src="/static/icons/selected.png" 
              mode="widthFix" 
              class="reason-check"
              v-if="selectedReasonId === item.id"
            ></image>
          </view>
        </view>
        <view class="popup-buttons">
          <view class="cancel-btn" @click="closeReasonPopup">取消</view>
          <view class="confirm-btn" @click="confirmReason">确定</view>
        </view>
      </view>
    </view>

    <!-- 提交成功弹窗 -->
    <view class="success-popup" v-if="showSuccessPopup">
      <view class="popup-mask" @click="hideSuccessPopup"></view>
      <view class="popup-container">
        <view class="popup-icon">
          <image src="/static/icons/success.png" mode="widthFix"></image>
        </view>
        <view class="popup-message">申请提交成功</view>
        <view class="popup-desc">我们将在1-3个工作日内处理您的退款申请</view>
        <view class="popup-btn" @click="gotoOrderDetail">查看订单</view>
      </view>
    </view>
  </view>
</template>

<script>
import { creditOrderefundr , userCouponapply } from '@/core/api/index.js'

export default {
  data() {
    return {
      type: 0,
      orderInfo: {},
      refundForm: {
        description: ""
      },
      reasonList: [
        { id: 1, text: "商品质量问题" },
        { id: 2, text: "尺寸/规格不符" },
        { id: 3, text: "商品与描述不符" },
        { id: 4, text: "拍错/多拍" },
        { id: 5, text: "商品破损/瑕疵" },
        { id: 6, text: "其他原因" }
      ],
      selectedReasonId: null,
      selectedReason: null,
      isReasonPopupVisible: false,
      showSuccessPopup: false
    };
  },
  computed: {
    // 商品图片URL
    goodsImageUrl() {
      const baseUrl = this.type 
        ? (this.orderInfo.productCoverImage || '') 
        : (this.orderInfo.iconUrl || '');
      return this.fixImageUrl(baseUrl) || '/static/default_img.png';
    },
    
    // 商品名称
    goodsName() {
      return this.type 
        ? (this.orderInfo.productName || '商品名称') 
        : (this.orderInfo.title || '优惠券名称');
    },
    
    // 商品价格
    goodsPrice() {
	  console.log(this.orderInfo.paidAmount,'金额')
      if (this.type && this.orderInfo.paidCredit !== undefined) {
        return `¥${Number(this.orderInfo.paidCredit).toFixed(2)}积分`;
      }
      return this.type ? '¥0.00' : (this.orderInfo.paidAmount ? `¥${this.orderInfo.paidAmount}` : '¥0.00');
	  
    },
    
    // 退款金额
    refundAmount() {
      if (this.type && this.orderInfo.paidCredit !== undefined) {
        return `¥${Number(this.orderInfo.paidCredit).toFixed(2)}`;
      }
      return this.type ? '¥0.00' : (this.orderInfo.paidAmount ? `¥${this.orderInfo.paidAmount}` : '¥0.00');
    },
    
    // 应退金额
    shouldRefundAmount() {
      if (this.type && this.orderInfo.paidCredit !== undefined) {
        return `${Number(this.orderInfo.paidCredit).toFixed(2)}积分`;
      }
      return this.type ? '0.00积分' : (this.orderInfo.paidAmount ? `￥${this.orderInfo.paidAmount}` : '￥0.00');
    },
    
    // 退款说明字数统计
    descCount() {
      return `${this.refundForm.description.length}/200`;
    }
  },
  onLoad(r) {
    console.log('路由参数:', r);
    
    // 初始化type参数
    this.type = r.type !== undefined ? Number(r.type) : 0;
    
    // 安全解析订单数据
    try {
      this.orderInfo = JSON.parse(decodeURIComponent(r.item)) || {};
      console.log('解析后的订单数据:', this.orderInfo);
    } catch (e) {
      console.error('解析订单数据失败:', e);
      uni.showToast({
        title: '加载订单信息失败',
        icon: 'none'
      });
      this.orderInfo = {};
    }
    
    // 修正图片路径
    if (this.type && this.orderInfo.productCoverImage) {
      this.orderInfo.productCoverImage = this.fixImageUrl(this.orderInfo.productCoverImage);
    } else if (!this.type && this.orderInfo.iconUrl) {
      this.orderInfo.iconUrl = this.fixImageUrl(this.orderInfo.iconUrl);
    }
  },
  methods: {
    // 修复图片URL
    fixImageUrl(url) {
      if (!url) return '';
      return url.startsWith('http') ? url : 'https:' + url;
    },
    
    // 打开退款原因弹窗
    openReasonPopup() {
      this.isReasonPopupVisible = true;
    },

    // 关闭退款原因弹窗
    closeReasonPopup() {
      this.isReasonPopupVisible = false;
    },

    // 选择退款原因
    selectReason(id, text) {
      this.selectedReasonId = id;
      this.selectedReason = text;
    },

    // 确认选择退款原因
    confirmReason() {
      if (this.selectedReasonId) {
        this.closeReasonPopup();
      }
    },

    // 提交退款申请
    async submitRefund() {
      if (!this.selectedReason) {
        uni.showToast({
          title: "请选择退款原因",
          icon: "none"
        });
        return;
      }

      // 显示加载中
      uni.showLoading({
        title: "提交中...",
        mask: true
      });

    
        // const data = await creditOrderefundr({
        //   id: this.orderInfo.id,
        //   refundReason: this.selectedReason,
        //   refundRemark: this.refundForm.description
        // });
		  try {
		    let data;
		    if (this.type) {
		      data = await creditOrderefundr({
		        id: this.orderInfo.id,
		        refundReason: this.selectedReason,
		        refundRemark: this.refundForm.description
		      });
		    } else {
		      data = await userCouponapply({
		        id: this.orderInfo.id,
		        refundReason: this.selectedReason,
		        refundRemark: this.refundForm.description
		      });
		    }
		
		    // 统一处理返回结果
		    if (data.code === '00000') { // 确认正确的成功码格式
			  uni.showModal({
			  	title: '提示',
			  	content: '您的退钱申请已成功提交，我们正在加急处理中～一般 1-2 个工作日内会给出审核结果，感谢您的理解与配合～',
				confirmText:"知道了",
				showCancel:false,
			  	success: function (res) {
			  		if (res.confirm) {
						uni.navigateBack({data:1})
			  			console.log('用户点击确定');
			  		} else if (res.cancel) {
			  			console.log('用户点击取消');
			  		}
			  	}
			  });
		      // this.showSuccessPopup = true;
		    } else {
			  uni.showModal({
			  	title: '提示',
			  	content: data.message,
				confirmText:"知道了",
				showCancel:false,
			  	success: function (res) {
			  		if (res.confirm) {
			  			console.log('用户点击确定');
			  		} else if (res.cancel) {
			  			console.log('用户点击取消');
			  		}
			  	}
			  });
		    }
		  } catch (error) {
		    console.error('退款申请错误:', error);
		    uni.showToast({
		      title: "网络错误，请重试",
		      icon: "none"
		    });
		  } finally {
		    uni.hideLoading();
		  }
    
    },

    // 隐藏成功弹窗
    hideSuccessPopup() {
      this.showSuccessPopup = false;
    },

    // 跳转到订单详情页
    gotoOrderDetail() {
      this.hideSuccessPopup();
      uni.navigateBack({
        delta: 1
      });
    }
  }
};
</script>

<style lang="scss" scoped>
// 基础变量
$primary-color: #F26B2E;
$text-color: #333;
$text-gray: #999;
$border-color: #f5f5f5;
$bg-color: #f5f5f5;
$btn-radius: 40rpx;

.refund-page {
  min-height: 100vh;
  background-color: $bg-color;
  padding: 20rpx;
  padding-bottom: 160rpx;
}

// 订单信息
.order-info {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .order-goods {
    display: flex;
    align-items: center;
    margin-bottom: 25rpx;

    .goods-img {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
      object-fit: cover;
    }

    .goods-info {
      margin-left: 20rpx;
      flex: 1;

      .goods-name {
        font-size: 28rpx;
        color: $text-color;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .goods-price {
        font-size: 30rpx;
        color: $primary-color;
        font-weight: 500;
        margin-top: 10rpx;
      }
    }
  }

  .order-amount {
    padding-top: 25rpx;
    border-top: 1rpx solid $border-color;

    .order-amount_price {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .amount-label {
      font-size: 28rpx;
      font-weight: 600;
      color: $text-color;
    }

    .amount-value {
      font-size: 32rpx;
      color: $primary-color;
      font-weight: 500;
    }

    .msg {
      font-size: 24rpx;
      color: $text-gray;
      margin-top: 15rpx;
    }
  }
}

// 退款原因
.refund-reason {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .order-amount_price {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .reason-label {
    font-size: 28rpx;
    font-weight: 600;
    color: $text-color;
    position: relative;

    image {
      position: absolute;
      right: -15%;
      top: 50%;
      transform: translateY(-50%);
      width: 12rpx;
    }
  }

  .reason-value {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: $text-color;

    image {
      width: 12rpx;
      margin-left: 10rpx;
    }
  }

  .msg {
    font-size: 24rpx;
    color: $text-gray;
    margin-top: 20rpx;
  }
}

// 退款说明
.refund-description {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .desc-label {
    font-size: 28rpx;
    font-weight: 600;
    color: $text-color;
    margin-bottom: 20rpx;
  }

  .desc-input {
    width: 100%;
    min-height: 160rpx;
    font-size: 26rpx;
    color: $text-color;
    line-height: 1.6;
    padding: 20rpx;
    border: 1rpx solid #e5e5e5;
    border-radius: 10rpx;
    box-sizing: border-box;
  }

  .desc-count {
    text-align: right;
    font-size: 22rpx;
    color: $text-gray;
    margin-top: 15rpx;
  }
}

// 底部按钮区域
.cofitng {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 25rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1rpx solid $border-color;

  .prce {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    font-weight: 600;
    color: $primary-color;

    view:first-child {
      color: $text-color;
      font-weight: 400;
      margin-right: 10rpx;
    }
  }

  .btn {
    width: 200rpx;
    height: 80rpx;
    background-color: $primary-color;
    color: #fff;
    border-radius: $btn-radius;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: 500;
    box-shadow: 0 4rpx 12rpx rgba($primary-color, 0.2);
  }
}

// 退款原因弹窗
.reason-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;

  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .popup-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding: 30rpx 0;

    .popup-title {
      font-size: 32rpx;
      color: $text-color;
      font-weight: 600;
      text-align: center;
      padding: 20rpx 0;
      position: relative;
    }

    .reason-options {
      max-height: 500rpx;
      overflow-y: auto;
      padding: 0 30rpx;

      .reason-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 25rpx 0;
        border-bottom: 1rpx solid $border-color;
        font-size: 28rpx;
        color: $text-color;

        &:last-child {
          border-bottom: none;
        }

        &.active {
          color: $primary-color;
        }

        .reason-check {
          width: 28rpx;
          height: 28rpx;
        }
      }
    }

    .popup-buttons {
      display: flex;
      margin-top: 20rpx;
      padding: 0 30rpx;

      .cancel-btn,
      .confirm-btn {
        flex: 1;
        height: 80rpx;
        border-radius: $btn-radius;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        font-weight: 500;
        margin: 0 15rpx;
      }

      .cancel-btn {
        border: 1rpx solid #e5e5e5;
        color: $text-gray;
      }

      .confirm-btn {
        background-color: $primary-color;
        color: #fff;
      }
    }
  }
}

// 成功弹窗
.success-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;

  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .popup-container {
    position: relative;
    width: 80%;
    max-width: 600rpx;
    background-color: #fff;
    border-radius: 24rpx;
    padding: 50rpx 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .popup-icon {
      width: 100rpx;
      height: 100rpx;
      margin-bottom: 30rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .popup-message {
      font-size: 32rpx;
      color: $text-color;
      font-weight: 600;
      margin-bottom: 15rpx;
    }

    .popup-desc {
      font-size: 26rpx;
      color: $text-gray;
      line-height: 1.6;
      margin-bottom: 40rpx;
    }

    .popup-btn {
      width: 100%;
      height: 80rpx;
      background-color: $primary-color;
      color: #fff;
      border-radius: $btn-radius;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      font-weight: 500;
    }
  }
}
</style>